//
//  FirstViewController.m
//  BeanTrip
//
//  Created by dlios on 15-6-29.
//  Copyright (c) 2015年 PandaGroup. All rights reserved.
//

#import "FirstViewController.h"

#define WIDTH ([UIScreen mainScreen].bounds.size.width/375)
#define HEIGHT ([UIScreen mainScreen].bounds.size.height/667)
#import "FirstCollectionViewCell.h"
#import "HTTPTool.h"
#import "FirstModel.h"
#import "FirstTopicCell.h"
#import "UIImageView+WebCache.h"
#import "FirstTopicModel.h"
#import "TopicViewController.h"
#import "TravelNotesViewController.h"
#import "MJRefresh.h"
#import "MBProgressHUD.h"
#import "TitleReusableView.h"
#import "SearchViewController.h"



@interface FirstViewController ()<UITextFieldDelegate,UICollectionViewDataSource,UICollectionViewDelegate>


@property(nonatomic, retain)NSMutableArray *picArr;
@property(nonatomic, retain)NSMutableArray *topicArr;
@property(nonatomic, retain)NSMutableArray *bannerArr;
@property(nonatomic, retain)UIScrollView *scrollView;
@property(nonatomic, retain)NSNumber *next_start;
@property(nonatomic, assign)BOOL isUpPull;
@property(nonatomic, retain)UICollectionView *collectionView;
@property(nonatomic, retain)MBProgressHUD *HUD;
@property(nonatomic, retain)UIAlertView *alert;
@property(nonatomic, retain)UIView *bacView;


@end

@implementation FirstViewController
- (void)dealloc
{
    [_picArr release];
    [_topicArr release];
    [_bannerArr release];
    [_collectionView release];
    [_scrollView release];
    [_alert release];
    [_HUD release];
    [_bacView release];
    [super dealloc];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
 

   // self.title = @"推荐";
    //自定义一个控件,继承自UITextField
    //创建搜索框对象
    // 创建首页上面的搜索按钮
    UIButton *mybutton = [UIButton buttonWithType:(UIButtonTypeCustom)];
    [self.view addSubview:mybutton];
    mybutton.frame = CGRectMake(10 * WIDTH, 5 * HEIGHT, self.view.frame.size.width - 20, 30 * HEIGHT);
    [mybutton addTarget:self action:@selector(pushActionn) forControlEvents:(UIControlEventTouchUpInside)];
    mybutton.layer.borderColor = [UIColor lightGrayColor].CGColor;
    [mybutton setTitleColor:[UIColor lightGrayColor] forState:(UIControlStateNormal)];
    mybutton.layer.cornerRadius = 8;
    mybutton.layer.borderWidth = 1;
    // 按钮上的label  用来显示文件
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(100 * WIDTH, 5 * HEIGHT, 200*WIDTH, 20 * HEIGHT)];
    label.text = @"请输入想搜索的游记";
    label.font = [UIFont systemFontOfSize:17*HEIGHT];
    label.textColor = [UIColor lightGrayColor];

    
    [mybutton addSubview:label];
    // 按钮上的图片
    UIImageView *imageV = [[UIImageView alloc] initWithFrame:CGRectMake(80 * WIDTH, 5 * HEIGHT, 18 * WIDTH, 18 * HEIGHT)];
    imageV.image = [UIImage imageNamed:@"add_new_poi_search_button"];
    [mybutton addSubview:imageV];
    self.navigationItem.titleView=mybutton;
    

    
    
    //新建一个collectionview
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
    flowLayout.itemSize = CGSizeMake(170 * WIDTH , 185 * WIDTH );
    flowLayout.minimumLineSpacing = 10  * ([UIScreen mainScreen].bounds.size.height / 667);
    flowLayout.sectionInset = UIEdgeInsetsMake(10 * WIDTH, 10 * HEIGHT, 0, 10 * HEIGHT);
    
    flowLayout.headerReferenceSize = CGSizeMake(0, 40 * HEIGHT);
    
    
    self.collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, WIDTH * 375, HEIGHT * 667 - 64 - 49) collectionViewLayout:flowLayout];
    self.collectionView.dataSource = self;
    self.collectionView.delegate = self;
    self.collectionView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:self.collectionView];
    [_collectionView release];
    
    //注册
    [self.collectionView registerClass:[FirstCollectionViewCell class] forCellWithReuseIdentifier:@"reuse"];
    
    [self.collectionView registerClass:[FirstTopicCell class] forCellWithReuseIdentifier:@"topic"];
    
    //注册头视图
    [self.collectionView registerClass:[TitleReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"sectionTitle"];
    
    
    
    //设置collectionview与上的距离
    self.collectionView.contentInset = UIEdgeInsetsMake(220 * HEIGHT , 0, 0, 0);
    
    
    
    //上拉加载
    
    self.isUpPull = NO;

    [self addFooder];
    self.picArr = [NSMutableArray array];
    self.topicArr = [NSMutableArray array];
    self.bannerArr = [NSMutableArray array];


    
    //
    //创建轮播图
    self.scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, -220 * HEIGHT, WIDTH * 375, 667 * HEIGHT/3)];
    [self.collectionView addSubview:self.scrollView];
    [_scrollView release];
    
    self.scrollView.pagingEnabled = YES;
    //设置偏移量
    self.scrollView.contentOffset = CGPointMake(WIDTH * 375, 0);
    //自动滚
    [NSTimer scheduledTimerWithTimeInterval:2 target:self selector:@selector(changeImage) userInfo:nil repeats:YES];

    
    //背景视图用于遮挡请求数据前的视图
    self.bacView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 375*WIDTH, 667*HEIGHT)];
    self.bacView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:self.bacView];
    [_bacView release];
    
     
    /**
     小菊花
     
     :returns: 图标
     */
    self.HUD = [[MBProgressHUD alloc] initWithView:self.view];
    [self.view addSubview:self.HUD];
    self.HUD.labelText = @"加载中";
    [self.HUD show:YES];

    
    [self createData];
    
}


- (void)addFooder
{
    __block FirstViewController *firstVC = self;
    [self.collectionView addFooterWithCallback:^{
        firstVC.isUpPull = YES;//标记为上拉操作
        [firstVC createData];
        
    }];

}


- (void)changeImage
{

    [self.scrollView setContentOffset:CGPointMake(self.scrollView.contentOffset.x + WIDTH * 375, 0) animated:YES];
    
    if (self.scrollView.contentOffset.x == WIDTH * 375 * (self.bannerArr.count - 1)) {
        self.scrollView.contentOffset = CGPointMake(WIDTH * 375, 0);
    }
}



//进行数据解析
- (void)createData
{
    //拼接网址
    NSString *strUrl = nil;
    if (self.isUpPull) {
        strUrl = [NSString stringWithFormat:@"http://api.breadtrip.com/v5/index/?is_ipad=0&lat=38.88283288586418&lng=121.5396614543071&next_start=%@&sign=0fcbf54b0aa6dfda8e64feb5efa7e8bf",self.next_start];
    }else{
        strUrl = @"http://api.breadtrip.com/v5/index/?is_ipad=0&lat=38.88283288586418&lng=121.5396614543071&sign=0fcbf54b0aa6dfda8e64feb5efa7e8bf";
    }
    
    [HTTPTool get:strUrl body:nil httpResult:JSON success:^(id result) {
        
        NSDictionary *dic = result;
        if (self.isUpPull == NO) {
            [self.picArr removeAllObjects];
            [self.topicArr removeAllObjects];
            
        }
        //把下拉的拼接网址关键字赋值
        self.next_start = dic[@"next_start"];
        NSArray *elementsArr = dic[@"elements"];
        for (NSDictionary *elementsDic in elementsArr) {
            if ([elementsDic[@"desc"] isEqualToString:@"热门游记"]) {
                NSArray *tempArr = elementsDic[@"data"];
                for (NSDictionary *dataDic in tempArr) {
                    //封装的方法
                
                FirstModel *firstModel = [[FirstModel alloc] init];
                
                [firstModel setValuesForKeysWithDictionary:dataDic];
                    [self.picArr addObject:firstModel];
                    [firstModel release];
                    
                }
            }else if ([elementsDic[@"desc"] isEqualToString:@"一个专题"]){
                
                NSArray *tempArr = elementsDic[@"data"];
                NSDictionary *dataDic = tempArr[0];
                FirstTopicModel *topic = [[FirstTopicModel alloc] initWithDic:dataDic];
                [self.topicArr addObject:topic];
                [topic release];
            
            
            }else if ([elementsDic[@"desc"] isEqualToString:@"广告banner"]){
                //广告轮播图
            NSArray *tempArr = elementsDic[@"data"];
            NSArray *detailArr = tempArr[0];
                
                [self.bannerArr addObject:[detailArr lastObject][@"image_url"]];
                for (NSInteger i = 0; i < detailArr.count; i++) {

                    [self.bannerArr addObject:detailArr[i][@"image_url"]];
                 }
                [self.bannerArr addObject:detailArr[0][@"image_url"]];
                
              }
        }
        
        //移除专题数组的最后一个对象
        if (self.isUpPull == NO && (self.topicArr.count % 2 != 0)) {
            [self.topicArr removeLastObject];
        }
        
        //给轮播图赋值
        //设置偏移量
        self.scrollView.contentSize = CGSizeMake(WIDTH * 375 * self.bannerArr.count, 0);
        //移除原有的图片
        for (NSInteger i = 0; i < self.scrollView.subviews.count; i++) {
            UIImageView *imageView = self.scrollView.subviews[i];
            [imageView removeFromSuperview];
            
        }
        //创建imageview
        for (NSInteger i = 0; i < self.bannerArr.count; i++) {
            UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(WIDTH*375 * i, 0, WIDTH*375, 200*HEIGHT)];
            [self.scrollView addSubview:imageView];
            [imageView sd_setImageWithURL:[NSURL URLWithString:self.bannerArr[i]] placeholderImage:[UIImage imageNamed:@"BeanTrip"]];
            [imageView release];
        }
        
        [self.collectionView footerEndRefreshing];
        [self.collectionView reloadData];
        //加载成功移除小菊花;
        [self.HUD removeFromSuperview];
        [self.bacView removeFromSuperview];
        
        } failure:^(NSError *error) {
            [self.bacView removeFromSuperview];
              
        [self.HUD removeFromSuperview];
        self.alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"网络不给力" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
              [self.alert show];
              [self.alert release];
              NSLog(@"%@",error);

    }];
}

//collectionView的方法
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    if (section == 0) {
        return self.topicArr.count;
    }else{
        return self.picArr.count;
    }
    
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 1) {
        //游记的cell
        FirstCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"reuse" forIndexPath:indexPath];
        if ([self.picArr isKindOfClass:[NSArray class]]) {
            
            FirstModel *firstModel = self.picArr[indexPath.row];
            //这里crash过,什么原因,lldb  已经解决  又出现了
            cell.nameLabel.text = firstModel.name;
            [cell.myImageView sd_setImageWithURL:[NSURL URLWithString:firstModel.cover_image_default] placeholderImage:[UIImage imageNamed:@"BeanTrip"]];
        }
        return cell;
    }else{
        //专题的cell
        FirstTopicCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"topic" forIndexPath:indexPath];
        FirstTopicModel *topic = self.topicArr[indexPath.row];
        cell.nameLabel.text = topic.cover_title;
        [cell.myImageView sd_setImageWithURL:[NSURL URLWithString:topic.cover] placeholderImage:[UIImage imageNamed:@"BeanTrip"]];
        return cell;
        
    }
}

- (void)pushActionn
{
    SearchViewController *search = [[SearchViewController alloc] init];
    [self.navigationController pushViewController:search animated:YES];
    [search release];

}

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return 2;
}

//collectionview的点击方法
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        TopicViewController *topic = [[TopicViewController alloc] init];
        //把URL传过去
        FirstTopicModel *topicModel = self.topicArr[indexPath.row];
        topic.urlStr = topicModel.url;
        topic.titleName = topicModel.cover_title;
        
        [self.navigationController pushViewController:topic animated:YES];
        
        
    }else{
        //把热门游记的id传到下一页
        TravelNotesViewController *travel = [[TravelNotesViewController alloc] init];
        FirstModel *mainModel = self.picArr[indexPath.row];
        travel.detailId = mainModel.turnNextId;
        //标题传过去
        travel.titleName = mainModel.name;
        [self.navigationController pushViewController:travel animated:YES];
        [travel release];
       
    }
}

- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
{
    TitleReusableView *view = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"sectionTitle" forIndexPath:indexPath];
    if (indexPath.section == 0) {
        view.titleLabel.text = @"本期专题";
        return view;
    }else{
    view.titleLabel.text = @"热门游记";
        return view;
    }
}




- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    //键盘回收
    [textField resignFirstResponder];
    return YES;
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
